package com.yueqian.web.controller;

import com.yueqian.pojo.Account;
import com.yueqian.service.AccountService;
import com.yueqian.web.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("findOne")
    public String findOne(Model model, String id) {
        Account account = accountService.findAccountById(Integer.parseInt(id));
        System.out.println(account);
        model.addAttribute("account", account);
        return "accountList";
    }

    @RequestMapping("findAll")
    public ModelAndView findAll() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("accountList");
        List<Account> list = accountService.findAll();
        mav.addObject("list", list);
        return mav;
    }

    //转账业务
    @RequestMapping("updateAccount")
    public String updateAccount(@RequestParam("fromName") String sourceName, @RequestParam("toName") String targetName, Double money) throws CustomException {
        try {
            accountService.update_Account(sourceName, targetName, money);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("转账失败，请联系管理员");
        }
        return "redirect:findAll";
    }

}
